package com.lepu.app.fun.grow.setting;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

import com.app.application.MyApplication;
import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.CallBack;
import com.core.lib.utils.geneal.UploadMenuImage;
import com.core.lib.utils.main.ImageUtilBase;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.CircularImageView;
import com.eyzhs.app.R;
import com.lepu.app.fun.grow.adapter.GrowSettingAlbumGalleryAdapter;
import com.lepu.app.fun.grow.fragment.FragmentGrow;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.main.permission.PermissionUtil;
import com.lepu.app.main.permission.callback.PermissionResultCallBack;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.GalleryFlow;

public class GrowSettingAlbumImageActivity extends BaseFragmentActivity
        implements OnTopbarNewLeftLayoutListener, AsyncRequest {

    private int mCurrentIndex = 0;
    public HashMap<Integer, String> mBitmapMap = new HashMap<Integer, String>();
    private GalleryFlow mGalleryFlow;

    @Override
    @SuppressLint("InflateParams")
    public void onCreate(Bundle savedInstanceState) {

        mNeedSwipeBack = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.grow_setting_image_activity);

        init();
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
    }

    private void init() {
        // topbar
        CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
        topbar.setTopbarTitle("设置相册封面");
        topbar.setonTopbarNewLeftLayoutListener(this);

        initGallery();
        Button saveButton = (Button) findViewById(R.id.saveButton);
        saveButton.setOnClickListener(mOnClickListener);
    }

    @SuppressWarnings("deprecation")
    private void initGallery() {
        mGalleryFlow = (GalleryFlow) findViewById(R.id.galleryFlow);
        final TextView galleryTitle = (TextView) findViewById(R.id.galleryTitle);

        final String[] titleArray = getResources().getStringArray(
                R.array.array_grow_setting_album_name);
        final ArrayList<String> dataList = new ArrayList<String>();
        for (int i = 0; i < titleArray.length; i++) {
            String path = String.format("image_album_cover/album_cover%d.jpg",
                    i);
            dataList.add(path);
        }
        GrowSettingAlbumGalleryAdapter adapter = new GrowSettingAlbumGalleryAdapter(
                this, dataList);
        mGalleryFlow.setAdapter(adapter);
        mGalleryFlow.setSelection(300);
        mGalleryFlow.setGravity(Gravity.CENTER);
        mGalleryFlow.setSpacing(10);

        mGalleryFlow.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {

                int selectIndex = position % dataList.size();
                galleryTitle.setText(titleArray[selectIndex]);

                mCurrentIndex = selectIndex;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                LogUtilBase.LogD("onNothingSelected", "onNothingSelected");
            }
        });

        mGalleryFlow.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                int selectIndex = position % dataList.size();
                mCurrentIndex = selectIndex;

                if (mCurrentIndex == 0) {
                    //default
                    return;
                }

                jumpCamera();

            }
        });
    }

    private void jumpCamera()
    {
        PermissionUtil.getInstance().request(this, new String[]{Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                },
                new PermissionResultCallBack() {
                    @Override
                    public void onPermissionGranted() {
                        //
                        String temp = SdLocal.getTempPhotoPath(GrowSettingAlbumImageActivity.this,
                                "temp_camera_icon");
                        UploadMenuImage.getInstance(GrowSettingAlbumImageActivity.this).setFilePath(
                                temp);
                        UploadMenuImage.getInstance(GrowSettingAlbumImageActivity.this).setIsCut(
                                true);
                        UploadMenuImage.getInstance(GrowSettingAlbumImageActivity.this)
                                .setIsPhotoDouble(false);

                        UploadMenuImage.getInstance(GrowSettingAlbumImageActivity.this)
                                .showPopAddPhoto();
                    }

                    @Override
                    public void onPermissionGranted(String... permissions) {
                        if (permissions == null || permissions.length == 0) {
                        }
                    }

                    @Override
                    public void onPermissionDenied(String... permissions) {
                        if (permissions != null) {

                        }
                    }

                    @Override
                    public void onRationalShow(String... permissions) {
                        if (permissions != null) {
                            UIHelper.showToast(GrowSettingAlbumImageActivity.this, R.string.permission_tip);
                            PermissionUtil.openSettingActivity(GrowSettingAlbumImageActivity.this);
                        }
                    }
                });
    }


    private View.OnClickListener mOnClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.saveButton:
                	
                	if(mCurrentIndex == 0)
                	{
                		UIHelper.showToast(GrowSettingAlbumImageActivity.this, "请选择其它的封面");
                		return;
                	}

                    boolean flag = MainTabActivity
                            .jumpLogin(GrowSettingAlbumImageActivity.this);
                    if (!flag) {

                        if (mBitmapMap != null && mBitmapMap.size() > 0
                                && mBitmapMap.get(mCurrentIndex) != null) {
                            // 合并图片
                            FrameLayout itemLayout = (FrameLayout) mGalleryFlow
                                    .findViewWithTag("cover_" + mCurrentIndex);
                            if (itemLayout != null) {
                                // Bitmap mergeBitmap = ImageUtilBase
                                // .getViewBitmap(itemLayout);

                                Bitmap firstBitmap = null;
                                if (mCurrentIndex == 1) {
                                    firstBitmap = ImageUtilBase.getBitmapByResId(
                                            GrowSettingAlbumImageActivity.this,
                                            R.drawable.album_cover0);
                                } else if (mCurrentIndex == 2) {
                                    firstBitmap = ImageUtilBase.getBitmapByResId(
                                            GrowSettingAlbumImageActivity.this,
                                            R.drawable.album_cover1);
                                } else if (mCurrentIndex == 3) {
                                    firstBitmap = ImageUtilBase.getBitmapByResId(
                                            GrowSettingAlbumImageActivity.this,
                                            R.drawable.album_cover2);
                                }

                                String path = SdLocal.getAlbumUserPath(
                                        GrowSettingAlbumImageActivity.this,
                                        SdLocal.DEFAULT_USER,
                                        "grow_setting_album_" + mCurrentIndex);

                                int width = UtilityBase.getDimenSize(
                                        GrowSettingAlbumImageActivity.this,
                                        R.dimen.modify_image_cover_width);
                                int height = UtilityBase.getDimenSize(
                                        GrowSettingAlbumImageActivity.this,
                                        R.dimen.modify_image_cover_height);
                                Bitmap twoBitmap = ImageUtilBase.createCircleImage(
                                        ImageUtilBase.zoomBitmap(
                                                ImageUtilBase.getBitmap(path), width,
                                                height), UtilityBase.getDimenSize(
                                                GrowSettingAlbumImageActivity.this,
                                                R.dimen.modify_image_cover_radius));

                                Bitmap mergeBitmap = ImageUtilBase.mergeBitmap(
                                        firstBitmap, twoBitmap,
                                        UtilityBase.getDimenSize(
                                                GrowSettingAlbumImageActivity.this,
                                                R.dimen.modify_image_cover_margin),
                                        UtilityBase.getDimenSize(
                                                GrowSettingAlbumImageActivity.this,
                                                R.dimen.modify_image_cover_margin));

                                LoginInfo loginInfo = MyApplication.getInstance()
                                        .getLoginInfo();
                                String coverPath = SdLocal.getAlbumUserPath(
                                        GrowSettingAlbumImageActivity.this,
                                        loginInfo.UserID, "album_cover");
                                ImageUtilBase.saveImageToSd(mergeBitmap, coverPath);

                                Map<String, Object> map = new HashMap<String, Object>();
                                JSONObject params = new JSONObject();
                                try {
                                    params.put("DeviceID", Setting.DEVICEID);
                                    params.put("ApplicationID",
                                            Setting.APPLICATIONID);
                                    params.put("UserID", loginInfo.UserID);
                                    params.put("LoginToken", loginInfo.LoginToken);

                                    params.put("AlbumFrameID", mCurrentIndex);
                                } catch (Exception e) {
                                }
                                map.put("ht", params);

                                HashMap<String, File> fileMap = new HashMap<String, File>();
                                fileMap.put("AlbumCover", new File(coverPath));

                                showProgressDialog();
                                ApiClient.http_post_main(
                                        Setting.getModiyAlbumCoverUrl(), map,
                                        fileMap,
                                        GrowSettingAlbumImageActivity.this, "",
                                        false);

                                // 更新成长喜悦的相册封面
                                FragmentGrow instance = FragmentGrow.getInstance();
                                if (instance != null) {
                                    instance.updateAlbumCover();
                                }
                            }
                        } else {
                            UIHelper.showToast(GrowSettingAlbumImageActivity.this,
                                    "请修改您的相册封面");
                        }

                    }
                    break;

                default:
                    break;
            }
        }
    };

    public void doWithImage(String filePath) {
        if (!TextUtils.isEmpty(filePath)) {
            // String path = SdLocal.getCacheImagePath(this,
            // "grow_setting_album_" + mCurrentIndex);
            // ImageUtilBase.saveImageToSd(ImageUtilBase.getBitmap(filePath),
            // path,
            // ImageUtilBase.IMAGE_QUALITY_MEDIUM);

            String path = SdLocal.getAlbumUserPath(this,
                    SdLocal.DEFAULT_USER, "grow_setting_album_"
                            + mCurrentIndex);
            try {
                // ImageCompressUtils.CompressImageFile(filePath, path);
                ImageUtilBase.saveImageToSd(ImageUtilBase.getBitmap(filePath),
                        path);

                if (mBitmapMap.containsKey(mCurrentIndex)) {
                    mBitmapMap.remove(mCurrentIndex);
                }
                mBitmapMap.put(mCurrentIndex, path);

                CircularImageView circularImageView = (CircularImageView) mGalleryFlow
                        .findViewWithTag(mCurrentIndex);
                if (circularImageView != null) {
                    Bitmap bit = ImageUtilBase.getBitmap(path, 200, 200);
                    if (bit != null) {
                        circularImageView.setImageBitmap(bit);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        UploadMenuImage.getInstance(this).onActivityResult(new CallBack() {
            @Override
            public void callBackSuccess(Object obj) {
                super.callBackSuccess(obj);

                doWithImage((String) obj);
            }
        }, requestCode, resultCode, data);

    }

    ;

    @Override
    public void onBackPressed() {
        finish(true);
    }

    @Override
    public void onTopbarLeftLayoutSelected() {
        finish(true);
    }

    @Override
    public void RequestComplete(Object object, Object data) {
        hideProgressDialog();
        finish(true);
    }

    @Override
    public void RequestError(Object object, int errorId, String errorMessage) {
        hideProgressDialog();
    }
}
